package com.ello.androidskeleton.view

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import com.ello.androidskeleton.R
import com.ello.androidskeleton.databinding.ViewTopBarBinding

/**
 * @author dxl
 * @date 2023-03-20
 */
class TopBar @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val vb = ViewTopBarBinding.inflate(LayoutInflater.from(context), this)

    init {
        val typedArray =
            context.theme.obtainStyledAttributes(attrs, R.styleable.TopBar, defStyleAttr, 0)
        val title = typedArray.getString(R.styleable.TopBar_main_title)
        val right = typedArray.getString(R.styleable.TopBar_right_text)
        val left = typedArray.getString(R.styleable.TopBar_left_text)
        typedArray.recycle()
        vb.tvTitle.text = title
        vb.tvRight.text = right
        vb.tvLeft.text = left
        vb.ivBack.setOnClickListener {
            if (context is Activity) {
                context.onBackPressed()
            }
        }
        vb.tvLeft.setOnClickListener { vb.ivBack.performClick() }
    }

    fun setTitle(text: String?) {
        vb.tvTitle.text = text
    }

    fun setRight(text: String?) {
        vb.tvRight.text = text
    }

    fun setRightClick(text: String? = null, onClickListener: OnClickListener) {
        if (text != null) {
            vb.tvRight.text = text
        }
        vb.tvRight.setOnClickListener(onClickListener)

    }

}